<template>
  <el-card shadow="never">
    <div class="edu-page-title">申请明细</div>
    <el-form
      ref="applyForm"
      :model="applyForm"
      label-width="150px"
      label-suffix="："
      :rules="rules"
    >
      <!-- <el-row :gutter="20">
        <el-col :span="10" ><div class="el-row-select-top-tips"> 该导师在当前用户入学时无导师资格。</div></el-col>
      </el-row> -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="申请原因" prop="applyReason">
            <el-select v-model="applyForm.applyReason" clearable style="width:100%">
              <el-option
                v-for="item in options.applyReason"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="转入导师" prop="newTeacherId">
            <el-select
              v-model="applyForm.newTeacherId"
              filterable
              clearable
              :remote-method="queryTeacher"
              @input="queryTeacherr"
              remote
              style="width:100%">
              <el-option
                v-for="item in teachersList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="原因说明" prop="reasonDescri">
            <el-input
              type="textarea"
              rows="3"
              maxlength="512"
              show-word-limit
              v-model="applyForm.reasonDescri"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="申请材料" prop="changeTutorEvid">
            <el-upload
              ref="uploadBtn"
              id="upload-btn"
              :data="{bucketname: 'face', folderpath: 'file'}"
              action="/api/commonservice/obsfile/uploadfile"
              :auto-upload="true"
              :on-success="handleUploadSuccess"
              :on-remove="handleUploadRemove"
              :before-upload="handleBeforeUpload"
              :on-error="handleUploadError"
              :on-exceed="handleUploadExceed"
              :on-change="handleUploadChange"
              multiple
              :limit="5"
              :file-list="fileList"
            >
              <div>
                <el-button size="small" type="primary">上传附件</el-button>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >上传要求：请上传jpg/png/word/pdf/xls等文件，且不超过5M
                </div>
                <div class="el-upload-file-tip" v-if="applyForm.applyReason == 3 || applyForm.applyReason == 4">
                 若申请原因为3、4的，请附上学院党政联席会意见
                 </div>
              </div>
            </el-upload>
            
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div align="right">
      <el-button @click="handleReturn">{{$t('message.return')}}</el-button>
      <el-button v-if="showSaveBtn" type="primary" @click="handleSave">{{$t('message.save')}}</el-button>
      <el-button type="primary" @click="handleSubmit">{{$t('message.submit')}}</el-button>
    </div>
    <edu-dialog
      :title="$t('message.prompt')"
      width="450px"
      :visible.sync="showDialog"
      :showFooter="false"
    >
      <div>返回将不会保存当前填写数据，是否确定？</div>
      <div class="float-right" style="margin:25px 0 0 0">
        <el-button @click="showDialog=false">{{$t("message.cancel")}}</el-button>
        <el-button @click="confirmReturn" type="primary">{{$t("message.confirm")}}</el-button>
        <el-button v-if="showSaveBtn" @click="saveAndClose" type="primary">保存并关闭</el-button>
      </div>
      <div style="clear:both"></div>
    </edu-dialog>
  </el-card>
</template>
<script>
  import {
    submitManageTotutor,
    createApplyInfoByStudent,
    editApplyInfoByStudent,
    batchSubmitManageToTutor,
    findTeacherList
  } from "common/src/api/culture/change";
  export default {
    name: "ApplyFormToTutor",
    props: {
      isNull: '',
      teacherName: '',
      options: {},
      showSaveBtn: {
        default: false,
        type: Boolean
      },
      students: {
        default: null
      },
      editForm: {
        default: null
      }
    },
    data: function() {
      return {
        fileList: [],
        files: [],
        teachersList: [], // 导师list
        fileSuccesList: [],
        uploadSuccess: true, //判断文件是否上传成功
        teachers: [],
        applyForm: {
          applyReason: null,
          newTeacherId: null,
          reasonDescri: null,
          changeTutorEvid: null,
          //申请人 id
          applicant:null,
          applicantapplicantName:null
        },
        rules: {
          applyReason: {
            required: true,
            message: "必须选择申请原因",
            trigger: "change"
          },
          newTeacherId: {
            required: true,
            message: "必须选择转入导师",
            trigger: "change"
          },
          reasonDescri: {
            required: true,
            message: "必须填写原因说明",
            trigger: "change"
          },
          changeTutorEvid: [
            {
              required: false,
              message: "必须上传申请材料",
              trigger: "change"
            },
            { validator: this.handleFileCheck, trigger: "change" }
          ]
        },
        isDraft: false, //是否草稿
        fileSuccessStatus: "success",
        showDialog: false
      };
    },
    mounted() {
      this.queryTeacherr(0);
      this.applyForm.changeTutorEvid = ''
      this.files = []
      /*alert(this.oldTeacher)*/
      if (this.editForm) {
        Object.keys(this.applyForm).forEach(key => {
          if (this.editForm.hasOwnProperty(key)) {
            this.applyForm[key] =
              typeof this.editForm[key] === "number"
                ? this.editForm[key].toString()
                : this.editForm[key];
          }
        });
        // this.fileList = this.applyForm.changeTutorEvid.split(",").map(fileName => {
        //   return { name: fileName };
        // });
        if(this.applyForm.changeTutorEvid && this.applyForm.changeTutorEvid.length > 0) {
          JSON.parse(this.applyForm.changeTutorEvid).forEach(file=> {
            this.fileList.push(
              {
                name: file.name,
                url: file.url
              }
            )
            this.files.push(
              {
                name: file.name,
                url: file.url
              }
            )
          })
        }
      }
      this.applyForm.newTeacherId = this.teacherName;
    },
    methods: {
      init() {
        //初始化申请明细
        this.applyForm.applyReason = null;
        this.applyForm.newTeacherId = null;
        this.applyForm.reasonDescri = null;
        this.applyForm.changeTutorEvid = null;
        this.$nextTick(() => {
          this.$refs.applyForm.clearValidate();
        });
        if (this.$refs.uploadBtn) {
          this.$refs.uploadBtn.clearFiles();
          this.fileList = [];
          // this.fileSuccesList.length = 0;
        }
      },
      handleReturn() {
        let changed = false;
        //新增
        if (this.editForm == null) {
          if (
            Object.keys(this.applyForm).some(
              key =>
                this.applyForm[key] != null &&
                _.trim(this.applyForm[key]) != ""
            )
          ) {
            changed = true;
          }
        } else {
          Object.keys(this.applyForm).forEach(key => {
            if (
              this.editForm.hasOwnProperty(key) &&
              this.applyForm[key] != this.editForm[key]
            ) {
              changed = true;
            }
          });
        }
        if (changed) {
          this.showDialog = true;
        } else {
          this.$emit("close");
        }
      },
      confirmReturn() {
        this.showDialog = false;
        this.$emit("close");
      },
      saveAndClose() {
        this.showDialog = false;
        if (this.showSaveBtn) {
          this.handleSave();
        } else {
          this.handleSubmit();
        }
      },
      // 导师数据(模糊查询)
      /*queryTeacher(val) {
        alert(val)
          this.teachersList = [];
          let condition = val.replace(/(^\s*)|(\s*$)/g, ""); // 去两边空格
          findTeacherList({keyWord: condition}).then(res => {
              if (res.code == 200) {
                  this.teachersList = res.data.map((item) => {
                      return {
                          label: item.name + "(" + item.code + ")",
                          value: item.code
                      }
                  })
              } else {
                  throw res.code;
              }
          });
      },*/
      queryTeacher(vale) {
        /*alert(vale)*/
        let val = vale + '';
        if(val.indexOf('(') >= 0) {
          val = val.substring(val.indexOf('(') + 1, val.indexOf(')'));
        }
        /*val = '00013';*/
        this.teachersList = [];
        let condition = val.replace(/(^\s*)|(\s*$)/g, ""); // 去两边空格
        findTeacherList({keyWord: condition}).then(res => {
          if (res.code == 200) {

            this.teachersList = res.data.map((item) => {
              return {
                label: item.name + "(" + item.code + ")",
                value: item.code
              }
            })
          } else {
            throw res.code;
          }
        });
      },
      queryTeacherr(vale) {
        /*alert(vale)*/
        if (vale === ''){
          vale = '0';
        } ;
        let val = vale + '';
        if(val.indexOf('(') >= 0) {
          val = val.substring(val.indexOf('(') + 1, val.indexOf(')'));
        }
        /*val = '00013';*/
        this.teachersList = [];
        let condition = val.replace(/(^\s*)|(\s*$)/g, ""); // 去两边空格
        findTeacherList({keyWord: condition}).then(res => {
          if (res.code == 200) {

            this.teachersList = res.data.map((item) => {
              return {
                label: item.name + "(" + item.code + ")",
                value: item.code
              }
            })
          } else {
            throw res.code;
          }
        });
      },
      handleSave() {
        let _this = this
        this.$refs.applyForm.validate(valid => {
          if (!valid) {
            return;
          }
          this.isDraft = true;
          //判断是否存在未上传文件
          // if (!_this.fileList.some(f => f.percentage !== 100)) {
          //   let files = _this.fileList.map(f => {
          //     return f.name;
          //   });
          //   _this.saveOrSubmit(files);
          // } else {
          //   // this.fileSuccesList.length = 0;
          //   // this.$refs.uploadBtn.submit();
          // }
          if(this.uploadSuccess) {
              this.saveOrSubmit(_this.files);
            } else {
              this.$message.error('文件未上传成功')
              this.isDraft = false;
            }
        });
      },
      saveOrSubmit(files) {
        let fn = res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: this.isDraft
                ? this.$t("message.saveSuccess")
                : this.$t("message.submitSuccess")
            });
            this.applyForm.changeTutorEvid = ''
            this.files = []
            this.$emit("close");
          }
        };
         
        //获取当提前系统申请人
        let user = this.$store.state.session.mockUser;
        this.userInfo = user ? user : JSON.parse(localStorage.getItem("user"));
        this.applyForm.applicant = this.userInfo.uid;
        this.applyForm.applicantName = this.userInfo.name;
        let params = _.cloneDeep(this.applyForm);
        if (params.newTeacherId.indexOf('(') >= 0) {
          params.newTeacherId = params.newTeacherId.substring(params.newTeacherId.indexOf('(') + 1,
            params.newTeacherId.indexOf(')'));
        }
        params.changeTutorEvid = JSON.stringify(files)
        
        /*alert(this.students.length);*/
        if (this.students.length == 1) {
          params.studentId = this.students[0].studentId;
          params.studentName = this.students[0].studentName;
          this.doSumbitByoneStu(params, fn);
        } else {
          params.studentInfoList = this.students.map(s => {
            return {
              studentId: s.studentId,
              studentName: s.studentName
            };
          });
          batchSubmitManageToTutor(params).then(fn);
        }
      },
      handleSubmit() {
        let _this = this
        this.$refs.applyForm.validate(valid => {
          /*alert(valid);*/
          if (!valid) {
            return;
          }
          if(_this.uploadSuccess) {
              _this.saveOrSubmit(_this.files);
            } else {
              _this.$message.error('文件未上传成功')
            }
          // _this.isDraft = false;
          // //判断是否存在未上传文件
          // if (_this.isNull === '1') {
          //   if (_this.fileList.some(f => f.percentage != null)) {
          //     /*alert('来了');*/
          //     let files = _this.fileList.map(f => {
          //       return f.name;
          //     });
          //     _this.saveOrSubmit(files);
          //   } else {
          //     // _this.fileSuccesList.length = 0;
          //     // _this.$refs.uploadBtn.submit();
          //   }
          // }else {
          //   // if (!_this.fileList.some(f => f.percentage != null)) {
          //   //   /*alert('来了');*/
          //   //   let files = _this.fileList.map(f => {
          //   //     return f.name;
          //   //   });
          //   //   _this.saveOrSubmit(files);
          //   // } else {
          //   //   // _this.fileSuccesList.length = 0;
          //   //   // _this.$refs.uploadBtn.submit();
          //   // }
            
          // };

        });
      },
      handleBeforeUpload() {
        this.uploadSuccess = false

      },
      handleUploadExceed() {
        this.$message({
          type: "warning",
          message: "超出文件上传个数"
        });
      },
      handleUploadError(err) {
        this.$message({
          type: "error",
          message: err
        });
        if(this.files.length > 0) {
          this.uploadSuccess = true
        }
        
      },
      handleUploadSuccess(response, file, fileList) {
        // this.fileSuccesList.push(file);
        // if (this.fileSuccesList.length === this.fileList.filter(f => f.percentage != null).length) {
        //   let files = this.fileSuccesList.map(f => {
        //     return f.response.data[f.name].objectkey;
        //   });
        //   this.fileList.forEach(file => {
        //       files.push(file.name);
        //   });
        //   this.saveOrSubmit(files);
        // }

        // let files = response.data.map(res => {
        //     return res[file.name].objectkey;
        //   });
          this.fileList = fileList
            if(file.response && file.response.data) {
              let res = file.response.data
              let key0 = Object.keys(res)
              this.files.push({
                url: res[key0].objectkey,
                name: res[key0].fileName
                })
           }
          if(response.code === 200) {
            this.uploadSuccess = true
          }
          
          // this.saveOrSubmit(files);
      },
      doSumbitByoneStu(params, fn){
        params.id = this.editForm ? this.editForm.id : null;
        //isDraft 为 true 意为 保存或者修改,false 为管理员和教务员、学生提交
        if (this.isDraft){
          if (this.editForm) {
            editApplyInfoByStudent(params).then(fn);
          } else {
            createApplyInfoByStudent(params).then(fn);
          }
        } else {
          submitManageTotutor(params).then(fn);
        }

      },
      handleUploadRemove(file, fileList) {
        this.fileList = fileList;
        let spliceVal = ''
         if(file.response && file.response.data) {
              let res = file.response.data
              let key0 = Object.keys(res)
              spliceVal = res[key0].objectkey
           } else if(file.url) {
             spliceVal = file.url
           }
          //  this.files = JSON.parse(this.files)
        for(let i = 0; i < this.files.length; i++) {
          if(this.files[i].url === spliceVal) {
            this.files.splice(i,1)
          }
        }

        this.applyForm.changeTutorEvid = fileList.length == 0 ? null : true;
        this.$refs.applyForm.validate();
         
      },
      handleUploadChange(file, fileList) {
        this.fileList = fileList;
        this.applyForm.changeTutorEvid = true;
        this.$refs.applyForm.validate();
      },
      handleFileCheck(rule, value, callback) {
        let hasErr = false;
        //判断文件格式
        let exts = [
          ".doc",
          ".docx",
          ".jpg",
          ".png",
          ".xls",
          ".xlsx",
          ".pdf"
        ];
        for (const file of this.fileList) {
          if (file.status === "success") {
            continue;
          }
          let fileExtName = file.name
            .substring(file.name.lastIndexOf("."))
            .toLocaleLowerCase();
          if (!exts.includes(fileExtName)) {
            hasErr = true;
            break;
          }
        }
        if (hasErr) {
          callback(new Error("上传文件格式有错误"));
          return;
        }
        //判断文件大小
        for (const file of this.fileList) {
          if (file.status === "success") {
            continue;
          }
          if (!(file.size / 1024 / 1024 < 5)) {
            hasErr = true;
            break;
          }
        }
        if (hasErr) {
          callback(new Error("上传文件大小不能超过5M"));
          return;
        }
        callback();
      }
    }
  };
</script>
<style lang="scss" scoped>
  #upload-btn ::v-deep {
    .el-upload--text {
      margin-bottom: 15px;
      position: relative;
      top: 0;
    }
    button {
      display: inline-block;
    }
    .el-upload__tip {
      display: inline-block;
      line-height: 30px;
      margin: 0 0 0 10px;
    }
    .el-upload-file-tip {
      color: red;
      position: absolute;
      left: 0;
      top: 30px;
      font-size: 12px;
    }
    ::v-deep .el-upload-list {
      clear: both;
      width: 50%;
    }
  }
  .el-row-select-top-tips {
    margin-top: 16px;
    margin-bottom: 16px;
    margin-left: 150px;
    text-align: left;
    font-size: 14;
    color: red;
  }
</style>
